package com.smartcommunity.service.excel.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.smartcommunity.base.common.CacheMap;
import com.smartcommunity.bean.constant.Constant;
import com.smartcommunity.bean.entity.Role;
import com.smartcommunity.bean.entity.User;
import com.smartcommunity.bean.model.Pager;
import com.smartcommunity.controller.excel.model.*;
import com.smartcommunity.controller.excel.tool.FileUtil;
import com.smartcommunity.dao.building.BuildingMapper;
import com.smartcommunity.dao.excel.ExcelExportDao;
import com.smartcommunity.dao.village.HouseDao;
import com.smartcommunity.dao.village.RealCompanyDao;
import com.smartcommunity.elasticsearch.people.PeopleEsApi;
import com.smartcommunity.entity.ac.AccessDevice;
import com.smartcommunity.entity.building.BuildingListReq;
import com.smartcommunity.entity.house.HouseListHouseResp;
import com.smartcommunity.entity.people.People;
import com.smartcommunity.entity.people.RealPeopleHouse;
import com.smartcommunity.entity.people.RealPower;
import com.smartcommunity.entity.system.Organization;
import com.smartcommunity.entity.tag.Tag;
import com.smartcommunity.entity.vehicle.Vehicle;
import com.smartcommunity.entity.village.*;
import com.smartcommunity.lis.BimgClientPool;
import com.smartcommunity.service.CommonService;
import com.smartcommunity.service.excel.ExportExcelService;
import com.smartcommunity.service.village.VillageService;
import com.smartcommunity.utils.ArrayUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.*;

@Service
@Slf4j
public class ExportExcelServiceImpl implements ExportExcelService {

    @Autowired
    private ExcelExportDao excelExportDao;

    @Autowired
    private RealCompanyDao realCompanyDao;

    @Autowired
    private BuildingMapper buildingMapper;

    @Autowired
    private HouseDao houseDao;

    @Autowired
    CommonService commonService;

    @Autowired
    private BimgClientPool lis;

    @Autowired
    private HttpSession httpSession;

    @Autowired
    private VillageService villageService;

    @Autowired
    private PeopleEsApi peopleEsApi;

    @Override
    public List<Vehicle> listVehicle(VehicleModel model,String path) {

        String villageCode = model.getVillageCode();
        //判断小区code,为空则通过parentId查找所有小区
        if (StringUtils.isEmpty(villageCode)) {
            User user = getCurrenUser();
            if(!user.isAdmin()){
                villageCode = getVillageCodeByUser(user);
            }
            if (StringUtils.isNotEmpty(model.getParentId())) {
                String orgIds = commonService.getAllChildOrgId(model.getParentId());
                Map<String, Object> map = new HashedMap();
                map.put("orgId", orgIds);
                map.put("villageCode", villageCode);
                List<String> villageList = commonService.listVillageCodeByOrgId(map);
                //此行政区划节点下没有小区，则返回
                if (villageList == null || villageList.size() == 0) {
                    return null;
                }
                model.setVillageCode(ArrayUtils.toString(villageList).replace("'",""));
            }else{
                model.setVillageCode(villageCode);
            }
        }
        List<Vehicle> list = excelExportDao.listVehicle(model);
        path = path + "/照片/";
        for(Vehicle v :list){
            v.setCredentialTypeCN(CacheMap.CREDENTIAL_TYPE_MAP.get(v.getCredentialType()));
            //图片下载到本地
            if(!StringUtils.isEmpty(v.getCarPic())){
                try {
                    byte[] bytes= lis.downLoad(v.getCarPic());
                    FileUtil.writeFile(path,v.getPlateNo()+".jpg",bytes);
                } catch (Exception e) {
                    log.error("下载图片失败！",e);
                }
            }
        };
        return list;
    }

    @Override
    public List<RealCompany> exportCompany(BaseModel model,String path) {
        if(model.getVillageCode()==null){
            User user = getCurrenUser();
            if(!user.isAdmin()){
                String codes = getVillageCodeByUser(user);
                model.setVillageCode(codes==null?null:codes.replace("'",""));
            }
        }
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("villageCode",model.getVillageCode());
        paramMap.put("ids",model.getIds());
        paramMap.put("text",model.getText());
        List<RealCompany> list = realCompanyDao.listRealCompanies(paramMap);
        path = path + "/照片/";
        for(RealCompany p :list){
            //图片下载到本地
            if(!StringUtils.isEmpty(p.getCompanyPic())){
                try {
                    byte[] bytes= lis.downLoad(p.getCompanyPic());
                    FileUtil.writeFile(path,p.getCompanyName()+".jpg",bytes);
                } catch (Exception e) {
                    log.error("下载图片失败！",e);
                }
            }
        };
        return list;
    }

    @Override
    public List<RealCompanyPeople> exportVillagePerson(CompanyPersonModel model,String path) {
        if(model.getVillageCode()==null){
            User user = getCurrenUser();
            if(!user.isAdmin()){
                String codes = getVillageCodeByUser(user);
                model.setVillageCode(codes==null?null:codes.replace("'",""));
            }
        }
        List<RealCompanyPeople> list = excelExportDao.listCompanyPeople(model);
        path = path + "/照片/";
        for(RealCompanyPeople p :list){
            //图片下载到本地
            p.setSex(CacheMap.GENDER_MAP.get(p.getSex()));
            p.setCredentialTypeCN(CacheMap.CREDENTIAL_TYPE_MAP.get(p.getCredentialType()));
            if(!StringUtils.isEmpty(p.getIdCardPic())){
                try {
                    byte[] bytes= lis.downLoad(p.getIdCardPic());
                    FileUtil.writeFile(path,p.getCredentialNo()+".jpg",bytes);
                } catch (Exception e) {
                    log.error("下载图片失败！",e);
                }
            }
        };
        return list;
    }

    @Override
    public List<Building> exportBuilding(VillageModel model) {
        BuildingListReq buildingListReq = new  BuildingListReq();
        buildingListReq.setVillageCode(model.getVillageCode());
        buildingListReq.setIds(model.getIds());
        buildingListReq.setBuildingNo(model.getBuildingNo());
        return buildingMapper.list(buildingListReq);
    }

    @Override
    public List exportCamera(DeviceSearchModel model) {
        List entryList = null;
        String villageCode = "";
      /*  if(model.getVillageCode()==null){
            User user = getCurrenUser();
            if(!user.isAdmin())
                villageCode = getVillageCodeByUser(user);
        }*/

        if(model.getType()!=null && model.getType().equals(String.valueOf(TreeTypeEnum.ORG.getTypeVal()))){
            if (StringUtils.isNotEmpty(model.getCode())) {
                String orgIds = commonService.getAllChildOrgId(model.getCode());
                Map<String, Object> map = new HashedMap();
                map.put("orgId", orgIds);
                map.put("villageCode", villageCode);
                List<String> villageList = commonService.listVillageCodeByOrgId(map);
                //此行政区划节点下没有小区，则返回
                if (villageList != null ) {
                    villageCode = ArrayUtils.toString(villageList);
                }
            }
            model.setCode(villageCode.replace("'",""));
        }
        if(model.getCameraType()!=null&&model.getCameraType().equals("12")){
            entryList = excelExportDao.listDevice(model);
        }else{
            entryList = excelExportDao.listCamera(model);
        }
        return entryList;
    }

    @Override
    public List<AccessDevice> exportAcDevice(BaseModel model) {
        List<AccessDevice> list = excelExportDao.listAccessDevice(model);
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        list.forEach(d->{
            d.setDeviceTypeCN("门禁");
        });
        return list;
    }

    @Override
    public List<HouseListHouseResp> exportHouse(VillageModel model) {
        if(model.getVillageCode()==null){
            User user = getCurrenUser();
            if(!user.isAdmin()){
                String codes = getVillageCodeByUser(user);
                model.setVillageCode(codes==null?null:codes.replace("'",""));
            }
        }
        HouseListReq houseListHouseResp = new HouseListReq();
        houseListHouseResp.setVillageCode(model.getVillageCode());
        houseListHouseResp.setIds(model.getIds());
        List<HouseListHouseResp> list = houseDao.list(houseListHouseResp);
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        list.forEach(h->{
            h.setTypeDesc(CacheMap.HOUSE_TYPE_MAP.get(h.getType()));
        });
        return list;
    }

    @Override
    public List<People> exportPeople(PeopleModel model,String path) {
        People people = new People();
        String villageCode = model.getVillageCode();
        //判断小区code,为空则通过parentId查找所有小区
        if (StringUtils.isNotEmpty(villageCode)) {
            people.setVillageCode(villageCode);
        } else {
            User user = getCurrenUser();
            if(!user.isAdmin()){
                villageCode = getVillageCodeByUser(user);
            }
            if (StringUtils.isNotEmpty(model.getParentId())) {
                String orgIds = commonService.getAllChildOrgId(model.getParentId());
                Map<String, Object> map = new HashedMap();
                map.put("orgId", orgIds);
                map.put("villageCode", villageCode);
                List<String> villageList = commonService.listVillageCodeByOrgId(map);
                //此行政区划节点下没有小区，则返回
                if (villageList == null || villageList.size() == 0) {
                    return null;
                }
                people.setVillageCode(ArrayUtils.toString(villageList).replace("'",""));
            }else{
                people.setVillageCode(villageCode);
            }
        }
        people.setRemarks(model.getIds());
        people.setText(model.getText());
        people.setLabel(model.getLabel());
        people.setPeopleType(model.getPeopleType());
        people.setCredentialNo(model.getCredentialNo());
        //字典转换
        //List<People> list = excelExportDao.listPeoples(people);
        Pager<People> pager = peopleEsApi.listPage(people,1,65535);

        List<People> list = pager.getList();

        if (CollectionUtils.isNotEmpty(list)) {
            //构建标签信息
            buildLabel(list);
            //构建小区住址信息
            buildAddress(list, people.getVillageCode());
        }
        path = path + "/照片/";
        for(People p :list){
            p.setPeopleTypeName(CacheMap.PEOPLE_TYPE_MAP.get(p.getPeopleType()));
            p.setCredentialTypeCN(CacheMap.CREDENTIAL_TYPE_MAP.get(p.getCredentialType()));
            p.setNation(CacheMap.NATION_MAP.get(p.getNation()));
            //图片下载到本地
            if(!StringUtils.isEmpty(p.getIdCardPic())){
                try {
                    byte[] bytes= lis.downLoad(p.getIdCardPic());
                    FileUtil.writeFile(path,p.getCredentialNo()+".jpg",bytes);
                } catch (Exception e) {
                    log.error("下载图片失败！",e);
                }
            }
        };
        return list;
    }

    private void buildAddress(List<People> entryList, String villageCode) {
        List<String> villageCodeList = new ArrayList<String>();
        if(StringUtils.isNotEmpty(villageCode)) {
            villageCodeList = Arrays.asList(villageCode.replaceAll("'", "").split(","));
        }
        //如果人员存在多个小区，这里只显示一个小区的信息
        for (People peo : entryList) {
            if(CollectionUtils.isNotEmpty(peo.getDetailAddress())) {
                for(RealPeopleHouse realPeopleHouse : peo.getDetailAddress()) {
                    if(CollectionUtils.isEmpty(villageCodeList) || villageCodeList.contains(realPeopleHouse.getVillageCode())) {
                        peo.setVillageCode(realPeopleHouse.getVillageCode());
                        peo.setBuildingNo(realPeopleHouse.getBuildingNo());
                        peo.setUnitNo(realPeopleHouse.getUnitNo());
                        peo.setHouseNo(realPeopleHouse.getHouseNo());
                        peo.setResidenceAddress(realPeopleHouse.getDetailAddress());
                        //填充迁出状态，跟随小区的状态
                        peo.setIsLeave(realPeopleHouse.getMove());
                        break;
                    }
                }
            }
        }
    }

    private void buildLabel(List<People> entryList) {
        //封装数据
        for (People people : entryList) {
            if (CollectionUtils.isNotEmpty(people.getLableList())) {
                people.setPeopleTag(people.getLableList());
                StringBuffer labels = new StringBuffer();
                for (Tag tag : people.getLableList()) {
                    labels.append(tag.getTagName()).append(",");
                }
                people.setLabel(labels.subSequence(0, labels.length() - 1).toString());
            }
        }
    }


    @Override
    public List<RealPower> exportPower(PowerModel model,String path) {
        if(model.getVillageCode()==null){
            User user = getCurrenUser();
            if(!user.isAdmin()){
                String codes = getVillageCodeByUser(user);
                model.setVillageCode(codes==null?null:codes.replace("'",""));
            }
        }
        List<RealPower> list = excelExportDao.listRealPower(model);
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        path = path + "/照片/";
        for(RealPower p :list){
            p.setCredentialTypeCN(CacheMap.CREDENTIAL_TYPE_MAP.get(p.getCredentialType()));
            //图片下载到本地
            if(!StringUtils.isEmpty(p.getIdCardPic())){
                try {
                    byte[] bytes= lis.downLoad(p.getIdCardPic());
                    FileUtil.writeFile(path,p.getCredentialNo()+".jpg",bytes);
                } catch (Exception e) {
                    log.error("下载图片失败！",e);
                }
            }
        };
        return list;
    }

    @Override
    public List<OrganizationVillage> exportVillageOrg(BaseModel model) {
        if(model.getIds()==null){
            User user = getCurrenUser();
            if(!user.isAdmin()){
                Set orgSet = villageService.getOrgIdsByVillageCode(getVillageCodeByUser(user));
                Object[] array = orgSet.toArray();
                String ids = StringUtils.join(array, ",");
                model.setIds(ids);
            }
        }
        List<OrganizationVillage> list = excelExportDao.listVillageOrg(model);
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        list.forEach(o->{
            if(StringUtils.isEmpty(o.getParentCode())){
                o.setParentCode("-1");
            }
            if(!StringUtils.isEmpty(o.getMapCenter())){
                String[] strArray =  o.getMapCenter().split(",");
                if(strArray.length>=2){
                    o.setLon(strArray[0]);
                    o.setLat(strArray[1]);
                }
            }
        });
        return list;
    }

    @Override
    public List<Organization> exportOrg(BaseModel model) {
        if(model.getIds()==null){
            User user = getCurrenUser();
            if(!user.isAdmin()){
                Set orgSet = villageService.getOrgIdsByVillageCode(getVillageCodeByUser(user));
                Object[] array = orgSet.toArray();
                String ids = StringUtils.join(array, ",");
                model.setIds(ids);
            }
        }
        return excelExportDao.listOrg(model);
    }

    /**
     * 获取当前用户
     * @return
     */
    private User getCurrenUser() {
        User user = null;
        Object obj =  httpSession.getAttribute(Constant.USER_KEY);
        if(obj!=null) {
            user = JSON.parseObject(JSONObject.toJSONString(obj), User.class);
        }
        return user;
    }

    //获取用户关联角色权限的小区ID及行政区划ID
    private String getVillageCodeByUser(User user){
        String villageCode = "";
        List<String> villageCodeList = new ArrayList<>();
        for (Role role: user.getRoleList()) {
            villageCode = CacheMap.REL_ROLE_VILLAGE.get(role.getId());
            if(StringUtils.isEmpty(villageCode)){
                continue;
            }
            villageCodeList.addAll(Arrays.asList(villageCode.split(",")));
        }
        villageCode = ArrayUtils.toString(villageCodeList);
        return villageCode;
    }


}
